/**
 * Created by   :宁建浩
 * Created time :2017/5/10
 * File explain :支付页面
 */
require.config({
  baseUrl: "../../libs",
  paths: {
    jquery: ["jquery/jquery-1.11.3"],
    layer: ["layer/layer"],
    zui: ["zui/js/zui"],
    boot: ["bootstrap-3.3.7-dist/js/bootstrap"],
    config: ["../common/js/common-config"],
  }
});
require(["jquery"], function () {
  require(["layer", "zui", "boot", "config"], operationCodeFun)
});
//代码容器

function operationCodeFun() {
  var QHConfig = $("body").data("config");//公共文件
  var userInfo = QHConfig.getSearchDataFun();//获取地址栏参数
  var bankInfo = null;//存放选择的银行的信息
  var paySn = null;//生成订单后的支付订单流水号
  $(".pay-name").on("click", ".pay", chooseBankFun);//样式切换
  $(".choice-bank-name").on("click", ".choice-bank", otherBankFun);//选择其他银行
  $(".next-step-orange").on("click", nextStepPay);//下一步
  $("#id-balance").html(userInfo.balance);//账户余额
  $(".balance-always").html(userInfo.amount);//转账金额
  $(".click-recharge").on("click", jumpRechargeFun);//余额不足跳转到充值页面
  $(".look-account").on("click", showBill);//成功或失败支付后查看订单
  $(".forget-password").on("click",clickForgetPwd);//忘记密码
  $(".sensitize-orange-btn").on("click",clickBtn);//激活
  $("#id-pass-balance").on("focus",function() {
    if($(this).val() != "") {
      $(this).siblings(".clear-img").css("visibility","visible");//显示清除按钮
    }
  }).on("blur",function() {
    setTimeout(function(){
      $(".clear-img").css("visibility","hidden");//隐藏清除按钮
    },200)
  }).on("keyup",function() {
    if($(this).val() == "") {
      $(this).siblings(".clear-img").css("visibility","hidden");//隐藏清除按钮
    }else {
      $(this).siblings(".clear-img").css("visibility","visible");//显示清除按钮
    }
  });
  //点击的叉，清空内容
  $(".clear-img").on("click",function () {
    $("#id-pass-balance").val("");//清除内容
    $("#id-pass-balance").focus();
    $(this).css("visibility","hidden");
    return false;
  });
  layer.config({
    path: "../../libs/layer/"
  });
  //选择其他银行后下一步按钮
  $(".next-step").on("click", clickOtherBankFun);
  //选择余额下一步
  $(".confirm-payment-btn").on("click", clickBalanceFun);
  //返回我的账户
  $(".back-account").on("click", backMyAcount);
  //点击忘记密码
  $('.forget-password-notice').on("click",clickForgetPwd);
  // 选择银行列表pay-transfer
  if(userInfo.transfer=="TRANSFER"){
    $(".pay-transfer").html("转账");
  }
  rederMoreBank();
  function rederMoreBank() {
    //生成银行列表
    var msg = {//订单所需数据
      bizzSys: userInfo.bizzSys,//业务类型
      bizzSn: userInfo.bizzSn,//流水号
      amount:userInfo.amount,
      tradeType: userInfo.transfer,//交易类型
      orders: [
        {
          userCode: userInfo.accountName,//收款人
          amount: userInfo.amount,//收款金额
          tradeMemo: userInfo.tradeMemo//备注
        }
      ],
      operName: userInfo.operName//打款人
    };
    //添加银行卡
    $.ajax(tokenAjax({
      type: "get",
      async: false,
      url: QHConfig.url.selectChannelList + "PC",
      contentType: "application/json",
      success: function (data) {
        if (data.data) {
          var _data = data.data;
          renderBankInfo(_data);//渲染银行卡信息
        }
      }
    }));
    //如果是转账调生成订单接口
    if (userInfo.transfer == "TRANSFER") {
      //生成订单
      if(!userInfo.formBill){
        $.ajax(tokenAjax({
          type: "POST",
          async: false,
          contentType: "application/json",
          url: QHConfig.url.payPayment,
          data: JSON.stringify(msg),
          success: function (data) {
            if(data.status==400){
              if(data.message.indexOf("分钟")!=-1){
                $(".input-opportunity1").show();
                timeCountDown1(data.message)
              }else{
                layer.alert(data.message)
              }
            }else {
              paySn = data.data;//赋值流水号
            }
          }
        }));
      }
    }
  }

  //渲染银行
  function renderBankInfo(_data) {
    var oHtml = "";//代码容器
    //信息有误，不渲染
    if (!_data) {
      return;
    }
    for (var i = 0; i < _data.length; i++) {
      //默认为建行
      if (_data[i].code == "CCB" && _data[i].payType == "B2B_NB") {
        oHtml += `<div class="choice-bank active" data-bankjson='${JSON.stringify(_data[i])}'>
              <div class="choice-bank-detail">
                <div class="choice-bank-choose-active"></div>
                <img class="choice-bank-logo" src="${_data[i].logoPc}" alt="">
                <div class="choice-corporate-card active">${_data[i].type == 0 ? "企<br/>业<br/>" : "个<br/>人<br/>"}</div>
              </div>
            </div>`;
      } else {
        oHtml += `<div class="choice-bank" data-bankjson='${JSON.stringify(_data[i])}'>
              <div class="choice-bank-detail">
                <div class="choice-bank-choose"></div>
                <img class="choice-bank-logo" src="${_data[i].logoPc}" alt="">
                <div class="choice-corporate-card">${_data[i].type == 0 ? "企<br/>业<br/>" : "个<br/>人<br/>"}</div>
              </div>
            </div>`;
      }
    }
    $(".choice-bank-name").append(oHtml);
  }

  //选择其他银行后下一步点击回调
  function clickOtherBankFun() {
    var choosedBank = $(".choice-bank-name>.active");
    bankInfo = choosedBank.data("bankjson");
    $(".pay-choose-selected").find("img").attr("src", bankInfo.logoPc);
    $(".pay-choose-selected").attr({
      "data-banktype": bankInfo.payType, "data-channel": bankInfo.channelCode,
      "data-bankcode": bankInfo.bankCode, "data-bankpay": bankInfo.type, "data-bankid": bankInfo.id
    });
    //是否是银行卡
    if (bankInfo.type == 0) {
      $(".pay-choose-selected").find(".corporate-card").show();
    } else {
      $(".pay-choose-selected").find(".corporate-card").hide();
    }
  }

  //下一步
  function nextStepPay() {
    var balance = parseFloat(userInfo.balance.replace(/,/ig,""));
    var paytype = $("[data-choose='selected']").data("paytype");//判断是施小包还是网银支付
    if (paytype == "sxb") {
      if (balance < userInfo.amount) {
        $(".not-sufficient-funds").show();
      } else {
        $(".not-sufficient-funds").hide();
        $(".input-password-contanier").show().siblings(".pay-container").hide();
      }
    } else if (paytype == "bank") {
      payTypeBank();
    }
  }

  //跳转到充值页面回调
  function jumpRechargeFun() {
    window.location.href = `../project-recharge/project-recharge.html?userCode=${userInfo.userCode}`
  }

  //选择支付方式
  function chooseBankFun() {
    $(this).attr("data-choose", "selected").find(".pay-detail").addClass("active").find(".pay-choose").addClass("pay-choose-active")
      .removeClass("pay-choose").parents(".pay").siblings(".pay").attr("data-choose", "0").find(".pay-detail")
      .removeClass("active").find(".pay-choose-active").removeClass("pay-choose-active").addClass("pay-choose");
  }

  //选择其他银行点击事件回调
  function otherBankFun() {
    $(this).addClass("active").find(".choice-bank-choose").removeClass("choice-bank-choose")
      .addClass("choice-bank-choose-active").siblings(".choice-corporate-card").addClass("active")
      .parents(".choice-bank").siblings(".choice-bank").removeClass("active").find(".choice-bank-choose-active")
      .removeClass("choice-bank-choose-active").addClass("choice-bank-choose").siblings(".choice-corporate-card")
      .removeClass("active");
  }

  //选择余额下一步操作
  function clickBalanceFun() {
    var pwd = $("#id-pass-balance").val();
    var msg = {
      bizzSn: userInfo.bizzSn,//流水号
      bizzSys: userInfo.bizzSys,//支付类型
      payPass: pwd,//密码
      channel: "SELF",//余额支付为SELF
      payType: "BALANCE"//
    };
    userPayType(msg);
  }

  //查看订单跳转
  function showBill() {
    $(".wait-container").addClass("hide").siblings(".pay-container ").show();

  }

  //银行卡支付
  function payTypeBank() {
    var payData = {};
    var $el = $(".pay-choose-selected");
    payData.channel = $el.attr("data-channel");//支付通道
    payData.payType = $el.attr("data-banktype");//银行类型
    payData.bizzSn = userInfo.bizzSn;//支付流水
    payData.bizzSys = userInfo.bizzSys;//支付类型
    payData.returnUrl = getRootPath() + "/pay-result/pay-result.html";//成功回调地址
    userPayType(payData);
  }

  /*
   * 获取根目录地址
   * @author wangshuzhong
   * @Date   2017/5/12
   * */
  function getRootPath() {
    //获取当前网址，如： http://localhost:8083/uimcardprj/share/meun.jsp
    var curWwwPath = window.document.location.href;
    //获取主机地址之后的目录，如： uimcardprj/share/meun.jsp
    var pathName = window.document.location.pathname;
    var pos = curWwwPath.indexOf(pathName);
    //获取主机地址，如： http://localhost:8083
    var localhostPaht = curWwwPath.substring(0, pos);
    //获取带"/"的项目名，如：/uimcardprj
    var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
    return (localhostPaht + projectName);
  }

  //银行成功后跳转页面
  function layerNew(url) {
    window.open(url);
  }

  //余额成功后页面显示
  function layerOther(url) {
    layer.open({
      title: false,
      shade: 0.8,
      move: false,
      closeBtn: 0,
      resize: false,
      scrollbar: false,
      type: 2,
      area: ['100%', '100%'],
      content: url
    });
  }

  //返回我的账户
  function backMyAcount() {
    parent.parent.layer.closeAll();
  }

  //支付ajax
  function doPayFun(msg) {
    $.ajax(tokenAjax({
      type: "POST",
      url: QHConfig.url.doPay,
      data: JSON.stringify(msg),
      contentType: "application/json;charset=UTF-8",
      success: function (res) {
        if (res.status == 400) {
          $(".input-opportunity").html(res.message).show();
          if(res.message.indexOf("分钟")!=-1){
            $(".input-password-contanier").hide();
            $(".tautology").show();
            $(".sensitize-orange-btn").css("background","#eee");
            timeCountDown(res.message)
          }
        } else if (res.status == 200) {
          $(".input-password-contanier").hide();//输入密码页面隐藏
          $(".pay-container").hide();//支付页面隐藏
          var url = "";
          if (!msg.payPass) {
            url = res.data.url;
            $(".wait-container").removeClass("hide");//等待页面显示
            layerNew(url);
          } else {
            url = `../transfer-success/transfer-success.html?amount=${userInfo.amount}`;
            layerOther(url);
          }
        }
      }
    }));
  }

  //确定付款方式
  function userPayType(payData) {
    $.ajax(tokenAjax({
      type: "PUT",
      data: JSON.stringify(payData),
      url: QHConfig.url.getPayType,
      contentType: "application/json;charset=UTF-8",
      success: function (data) {
        var msg = {
          bizzSn: payData.bizzSn,
          bizzSys: payData.bizzSys
        };
        if(data.status==200){
          if (payData.payPass) {
            msg.payPass = payData.payPass
          }
          if (data.data == 1) {
            doPayFun(msg);
          }
        }else{
          layer.msg(data.message);
        }
      }
    }));
  }
  //忘记密码页面
  function clickForgetPwd(){
    layer.open({
      title: false,
      shade: 0.8,
      move: false,
      closeBtn: 0,
      resize: false,
      scrollbar: false,
      type: 2,
      area: ['100%', '100%'],
      content: "../forget-payment-password/forget-payment-password.html?pay=true"
    });
  }
  //倒计时
  function timeCountDown(msg){
    var minuteNum= msg.match(/\d/ig);
    var countDown=null;
    var m=0;
    var s=0;
    if(minuteNum[0]==1){
      m=9;
      s=59;
      $('.tautology-time').html(m + "分" + (s >= 10 ? s : "0" + s) +"秒");
      countDown=setInterval(function(){
        s--;
        $('.tautology-time').html(m + "分" + (s >= 10 ? s : "0" + s) +"秒");
        if(s<0){
          s=59;
          m--;
        }
        if(m==0&&s==1){
          $(".sensitize-orange-btn").css("background","#faa500");
          clearInterval(countDown);
        }
      },1000);
    }else{
      m=minuteNum[1];
      s=minuteNum[2]+minuteNum[3];
      $('.tautology-time').html(m + "分" + (s >= 10 ? s : "0" + s) +"秒");
      countDown=setInterval(function(){
        s--;
        $('.tautology-time').html(m + "分" + (s >= 10 ? s : "0" + s) +"秒");
        if(s<=0){
          s=59;
          m--;
        }
        if(m==0&&s==1){
          $(".sensitize-orange-btn").css("background","#faa500");
          clearInterval(countDown);
        }
      },1000);
    }

  }
  function timeCountDown1(msg){
    var minuteNum= msg.match(/\d/ig);
    var countDown=null;
    var m=0;
    var s=0;
    if(minuteNum[0]==1){
      m=9;
      s=59;
      $('#id-djs').html(m + "分" + (s >= 10 ? s : "0" + s) +"秒");
      countDown=setInterval(function(){
        s--;
        $('.tautology-time').html(m + "分" + (s >= 10 ? s : "0" + s) +"秒");
        if(s<0){
          s=59;
          m--;
        }
        if(m==0&&s==1){
          $(".input-opportunity1").hide();
          clearInterval(countDown);
        }
      },1000);
    }else{
      m=minuteNum[1];
      s=minuteNum[2]+minuteNum[3];
      $('#id-djs').html(m + "分" + (s >= 10 ? s : "0" + s) +"秒");
      countDown=setInterval(function(){
        s--;
        $('#id-djs').html(m + "分" + (s >= 10 ? s : "0" + s) +"秒");
        if(s<=0){
          s=59;
          m--;
        }
        if(m==0&&s==1){
          $(".input-opportunity1").hide();
          clearInterval(countDown);
        }
      },1000);
    }
  }
  //激活按钮
  function clickBtn(){
    if($(".tautology-time").html()=="0分00秒"){
      $(".input-password-contanier").show();
      $(".input-opportunity").hide();
      $(".tautology").hide();
    }
  }
}